<?php

class MediaController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='application.modules.admin.views.layouts.default';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','create2','catelist','folder','update','category'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		
		$model=new Media;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Media']))
		{
			$model->attributes=$_POST['Media'];
			
// 			UtilTools::dump($_REQUEST);
// 			UtilTools::dump($model->attributes);			
			
			
			if($model->save())
			{
				echo $this->createUrl('update', array('id'=>$model->media_id));
				Yii::app()->end();
			
// 				$this->redirect(array('view','id'=>$model->media_id));				
			}

		}
		
		$criteria = new CDbCriteria(array(
			'condition'=>'media_status != :media_status',
			'params' => array(
				':media_status' => Media::STATUS_TRASH
			)
		));
		
		$dataProvider=new CActiveDataProvider('Media',array(
			'criteria' => $criteria,
			'pagination' => array(
				'pageSize' => 6
			)
		));

		$this->render('create',array(
			'model'=> $model,
			'dataProvider' => $dataProvider
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Media']))
		{
			$model->attributes=$_POST['Media'];
			if($model->save())
			{
				die("ok");
// 				$this->redirect(array('view','id'=>$model->media_id));				
			}

		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	public function actionFolder($id)
	{
	
		$model = $this->loadModel($id);
		
		UtilTools::dump($model->attributes);
		
		if(isset($_GET['fid']))
		{
			$model->media_pic_id = $_GET['fid'];
			if($model->save())
			echo "ok";
		}
	
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$catelist = Category::model()->findAll(array(
		          'condition'=>'cate_type = '.Category::CATEGORY_MEDIA,
		          'order'=>'cate_id ASC ,cate_pid DESC',
		          'with'=>array('media'),
		 ));
		 
		 $catelist = Category::model()->getChildrenObject($catelist);
		   
		$criteria = new CDbCriteria(array(
			'condition' => 'media_status != :media_status',
			'params' => array(
				':media_status'=>Media::STATUS_TRASH
			)
		));
		
		 
		$dataProvider=new CActiveDataProvider('Media',array(
			'criteria' => $criteria,
			'pagination' => array(
				'pageSize' => 6
			)
		));
		
		$comments = Comment::model()->findAll(array(
			'condition'=>'com_mid IS NOT NULL',
			'order' => 'com_id DESC',
			'limit' =>5
		));
		
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
			'catelist'=>$catelist,
			'comments'=>$comments
		));
	}

// 	public function actionCategory()
// 	{
	
// 		$criteria = new CDbCriteria(
// 		array(
// 			'condition'=>'cate_type=:cate_type',
// 	        'order'=>'cate_type ASC,cate_pid ASC,cate_order DESC',
// 	        'params'=>array(
// 	        	':cate_type'=>Category::CATEGORY_MEDIA
// 				)
// 			)
// 		);
	
// 		$dataProvider=new CActiveDataProvider('Category',array(
// 	            'criteria'=>$criteria
// 		));
	
// 		$model=new Category;
	
// 		Uncomment the following line if AJAX validation is needed
// 		$this->performAjaxValidation($model);
	
	
// 		if(isset($_POST['Category']))
// 		{
// 			$count = Category::model()->count('cate_name = :cate_name',array(':cate_name'=>$_POST['Category']['cate_name']));
	
// 			if($count > 0)
// 			{
// 				die("exists");
// 			}
	
// 			$model->attributes=$_POST['Category'];
	
// 			           var_dump($model->attributes);
// 			           die();
	
// 			           try {
// 			           	$model->save();
// 			           }
// 			           catch (CException $e)
// 			           {
// 			           	$e->getMessage();
// 			           }
// 			if($model->save()){
// 				die("ok");
// 			}else{
// 				die("fail");
// 			}
				
// 		}
	
// 		$this->render('category',array(
// 				'model'=>$model,
// 				'dataProvider'=>$dataProvider
// 		));
// 	}

	public function actionCategory()
	{
	
		$criteria = new CDbCriteria(
			array(
		      'condition'=>'cate_type=:cate_type',
		      'order'=>'cate_type ASC,cate_pid ASC,cate_order DESC',
		      'params'=>array(
					':cate_type'=>Category::CATEGORY_MEDIA
				)
			)
		);
	
		$dataProvider=new CActiveDataProvider('Category',array(
	            'criteria'=>$criteria
		));
	
		$model=new Category;
	
		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);
	
	
		if(isset($_POST['Category']))
		{
			$count = Category::model()->count('cate_name = :cate_name',array(':cate_name'=>$_POST['Category']['cate_name']));
	
			if($count > 0)
			{
				die("exists");
			}
	
			//下面两行为修改过后的内容
			//start
			$cateModel = Category::model()->findByPk($_POST['Category']['cate_pid']);
	
			$model->cate_type = $cateModel->cate_type;
				
			//end
	
			$model->attributes=$_POST['Category'];
	
	
			//            var_dump($model->attributes);
			//            die();
	
			//            try {
			//            	$model->save();
			//            }
			//            catch (CException $e)
			//            {
			//            	$e->getMessage();
			//            }
			if($model->save()){
				die("ok");
			}else{
				die("fail");
			}
				
		}
	
		$this->render('category',array(
				'model'=>$model,
				'dataProvider'=>$dataProvider
		));
	}
	
	public function actionCateList()
	{
		$this->blackLayout();
		$criteria = new CDbCriteria(array(
				'condition'=>'cate_type = '.Category::CATEGORY_MEDIA,
		//			'limit'=>10,
		//			'offset'=>10*($_GET['page']-1),
		));
		$count = Category::model()->count($criteria);
	
		$pages = new CPagination($count);
		$pages->pageSize = 5;
		$pages->applyLimit($criteria);
	
		$posts = Category::model()->findAll($criteria);
		$posts = Category::model()->getChildrenObject($posts);
	
		$this->render('catelist',array(
				'pages'=>$pages,
				'posts'=>$posts
		));
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Media('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Media']))
			$model->attributes=$_GET['Media'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Media::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='media-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	protected function blackLayout()
	{
		return $this->layout='application.modules.admin.views.layouts.blank';
	}
	
	protected function baseLayout()
	{
		return $this->layout='application.modules.admin.views.layouts.base';
	}
}
